import React, {Component } from 'react';
import {Editor} from "react-draft-wysiwyg";
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

class RichTextEdit extends Component {
  state = {
    editorState: EditorState.createEmpty() //创建一个空的编辑器
  }
  render() {
    let {editorState} = this.state
    return (
      <div>
        <Editor
          editorState={editorState}
          toolbarStyle={{
            marginBottom: 0
          }}
          editorStyle={{
            border:"1px solid #F1F1F1",
            minHeight:'200px',
            lineHeight:'10px',
            padding:'10px'}}
          onEditorStateChange={this.onEditorStateChange}
        />
      </div>
    );
  }
  componentDidMount() {
    let txt = this.props.txt
    if (txt) {
      this.setRichText(txt)
    }
  }
  
  // 富文本编辑器内容改变事件
  onEditorStateChange = (editorState) => {
    this.setState({
      editorState
    })
    
    // 将内容传给父组件
    this.props.childrenRichText(this.getRichText())
  }
  
  // 获取富文本编辑器中数据
  getRichText = () => {
    let {editorState} = this.state
    return draftToHtml(convertToRaw(editorState.getCurrentContent()));
  }
  
  // 将内容设置到富文本编辑器中
  setRichText = (html) => {
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.setState({
        editorState
      })
    }
  }
}

export default RichTextEdit;
